"use strict";
var express = require('express');
var router = express.Router();
var Project = require('./../../model/Project.js');
var City = require('./../../model/City.js');
var q = require('q');
/** 
 * 根据权限列表,来对项目进行排序
 */
function filterLineListByAuthorListIntoCityList(lineList, authorizedList) {
    var cityList = [];
    lineList.forEach(function(line) {
        var prjList = line.projects.filter(function(project) {
            return authorizedList.indexOf(project.prjId) >= 0;
        });
        if (prjList.length > 0) {
            line.projects = prjList;
            var tempCity = cityList.find(function(item) {
                return item.name === line.city;
            });
            if (!tempCity) {
                tempCity = new City(line.city);
                tempCity.lines.push(line);
                cityList.push(tempCity);
            } else {
                tempCity.lines.push(line);
            }
        }
    });
    return cityList;
}

/**  获取前端的城市列表 */
router.get('/frontProjects', function(req, res, next) {
    q.all([Project.getFrontProjects(req.query), req.user.getAuthorizedProjects()])
        .then(function(dataList) {
            var cityList = filterLineListByAuthorListIntoCityList(dataList[0], dataList[1]);
            res.json(cityList);
        });
});

/** 获取该用户授权到的项目类型 */
router.get('/authorizedProjectTypes', function(req, res) {
    req.user.getAuthorizeProjectTypes().then(function(data) {
        res.send(data);
    });
});


module.exports = router;
